package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.Response;
import cn.zmit.kuxi.request.RequestTask;

/** * @author @parameter * @return */
public class ForgetPasswordActivity extends BaseActivity {
	@ViewInject(R.id.et_inpu_user_phone)
	private EditText et_inpu_user_phone;
	@ViewInject(R.id.et_inpu_verification_code)
	private EditText inpu_verification_code;
	@ViewInject(R.id.tv_get_forget_verification_code)
	private TextView get_verification_code;
	@ViewInject(R.id.edt_set_password)
	private EditText set_password;
	@ViewInject(R.id.edt_input_again_password)
	private EditText input_again_password;
	@ViewInject(R.id.btn_submit_and_login)
	private Button submit_and_login;
	@ViewInject(R.id.llRoot)
	private LinearLayout llRoot;
/**
 * 登录手机号码
 */
private String phone;
/**
 * 登录密码
 */
private String password;
/**
 * 验证码
 */
private String code;
/**
 * 验证码
 */
private String again_password;
private String flag;

@SuppressLint("HandlerLeak")
private Handler handler=new Handler(){
public void handleMessage(Message msg) {
	switch (msg.what) {
	case Constants.EXECUTE_LOADING:
		get_verification_code.setText(msg.arg1 + "秒后重新获取");
		if (msg.arg1==0) {
			closeTimer();
			get_verification_code.setTextColor(getResources().getColor(R.color.white));
			get_verification_code.setClickable(true);
		}
		break;
	case Constants.EXECUTE_FINISH:
		get_verification_code.setText("重新获取验证码");
		get_verification_code.setTextColor(getResources().getColor(R.color.white));
		break;
	default:
		break;
	}
	
};
};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitleView("忘记密码", true);
		setContentView(R.layout.activity_forget_password);
		ViewUtils.inject(this);
		flag=getTextFromBundle("flag");
		llRoot.setOnTouchListener(new OnTouchListener() {//点击空白部分隐藏软键盘
			
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				
				return inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
			}
		});
	}
	@OnClick({R.id.tv_get_forget_verification_code,R.id.btn_submit_and_login})
	private void OnClick(View v){
		switch (v.getId()) {
		case R.id.btn_submit_and_login://提交并登陆
			if (checkForm()) {
				phone=et_inpu_user_phone.getText().toString().trim();
				code=inpu_verification_code.getText().toString().trim();
				password=set_password.getText().toString().trim();
			
				doSubmitPassword(phone, "2", code, password);
				openActivity(LoginActivity.class);
			}
			break;
		case R.id.tv_get_forget_verification_code://获取验证码
				if (verificationCheckForm()) {
					String type="2";
					phone=et_inpu_user_phone.getText().toString().trim();
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("phone", phone);
					map.put("type", type);
					RequestTask.getInstance().doSalt(this, map, new OnRequestListener());
					//请求结束开启倒计时
					get_verification_code.setTextColor(getResources().getColor(R.color.white));
					get_verification_code.setClickable(false);
					startTimer();
				}
				
			
			
			break;
		default:
			break;
		}
	}
	//获取验证码请求
	private class OnRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response, DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			dismissProgressDialog();
			JsonData jsonData = JsonData.create(response);

			ToastUtils.show(context, jsonData.optString(Response.MASSAGE));
		}

		@Override
		public void onRequestFailed(String error) {
			// TODO Auto-generated method stub
			super.onRequestFailed(error);
			dismissProgressDialog();
		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();
			showProgressDialog("正在获取验证码……");
		}
	}
	
	//执行
	private void doSubmitPassword(String phone,String type,String code,String password){
			Map<String, Object>map=new HashMap<String,Object>();
			map.put("phone", phone);
			map.put("type", type);
			map.put("salt", code);
			map.put("new_password", password);
			RequestTask.getInstance().doForgetPwd(this, map, new onSubRequestListener());
			
	}
	//提交请求
	private class onSubRequestListener extends OnRequestListenerAdapter<Object>{
		@Override
		public void onDone(XDroidRequest<?> request, String response, DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData=JsonData.create(response);
			if (jsonData.optString(Response.CODE).equals("0")) {
				ToastUtils.show(context, "密码重置成功");
				openActivity(LoginActivity.class);
			}else{
				ToastUtils.show(context, "密码重置失败");
			}
		}
	}
	//获取验证码时表单验证
	private Boolean verificationCheckForm(){
		phone=et_inpu_user_phone.getText().toString().trim();
		if (StringUtils.isEmpty(phone)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		}else if (!StringUtils.isPhone(phone)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		}
		return true;
	
		
	}
	//表单验证
	private Boolean checkForm(){
		phone=et_inpu_user_phone.getText().toString().trim();
		code=inpu_verification_code.getText().toString().trim();
		password=set_password.getText().toString().trim();
		again_password=input_again_password.getText().toString().trim();
		if (StringUtils.isEmpty(phone)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		}else if (!StringUtils.isPhone(phone)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		}else if (StringUtils.isEmpty(code)) {
			ToastUtils.show(context, "请输入验证码");
			return false;
		}else if (StringUtils.isEmpty(password)) {
			ToastUtils.show(context, "请输入密码");
			return false;
		}else if (!password.equals(again_password)) {
			ToastUtils.show(context, "两次输入的密码不同");
			return false;
		} else if (password.length() < 6 || password.length() > 20) {
			ToastUtils.show(this, "密码长度为6-20个字符");
			return false;
		} 
		
		return true;
	}
	//开启计时
	private int mTimerId = 60;

	private TimerTask timerTask;

	private Timer timer;
	private void startTimer(){
		if (timerTask==null) {
			timerTask=new TimerTask() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Message msg=new Message();
					msg.what=Constants.EXECUTE_LOADING;
					msg.arg1 = (int) (--mTimerId);
					handler.sendMessage(msg);
				}
			};
			timer = new Timer();
			timer.schedule(timerTask, 100, 1000);
		}
	}
	//结束计时
	private void closeTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask = null;
		}
		mTimerId = 60;
		handler.sendEmptyMessage(Constants.EXECUTE_FINISH);
	}
}
